package com.wust.baby.picture;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wust.R;

import com.wust.http.FormFile;
import com.wust.http.SocketHttpRequester;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.AbsListView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

/**
 * ImageSwitcher和Gallery如何展示SD卡中的资源图片
 * @author Andy.Chen
 * @email:Chenjunjun.ZJ@gmail.com
 */
public class ImageSwitcherAndGalleryDemoActivity extends Activity 
             implements OnItemSelectedListener,ViewFactory, OnItemClickListener {
    
	private List<String> imagePathList; 
	private String[] list; 
	private ImageSwitcher mSwitcher;
	private Gallery mGallery;
	private String firstURL=null;
	private String imagePath;
	private int index=0;
	private int mindex=0;
	private String imageName;
	private String user_id;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image);
        imagePathList=getImagePathFromSD(); 
        list = imagePathList.toArray(new String[imagePathList.size()]); 
        SharedPreferences preferences = getSharedPreferences("userinfo",0);
		user_id=preferences.getString("user_id", "");
		System.out.println("first activity usr:"+user_id);
        Intent intent=getIntent();
        firstURL=intent.getStringExtra("picPath");
       
		/* 设定Switcher */
		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mSwitcher.setFactory(this);
		/* 设定载入Switcher的模式 */
		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		/* 设定输出Switcher的模式 */
		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));
		mSwitcher.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				showDialog(ConstDefine.ICON_LIST_DIALOG);
				return false;
			}
		});
		mSwitcher.setImageURI(Uri.parse(firstURL));

		mGallery = (Gallery) findViewById(R.id.mygallery);
		/* 新增几ImageAdapter并设定给Gallery对象 */
		mGallery.setAdapter(new ImageAdapter(this, getImagePathFromSD()));

		mGallery.setOnItemSelectedListener(this);
		mGallery.setOnItemClickListener(this);
		index=getIndex(imagePathList);
		mindex=index;
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	 
         System.out.println("imageName:"+imageName);
    	super.onResume();
    }
    private int getIndex(List<String> li){
    	for(int i=0;i<li.size();i++){
    		if(firstURL.equals(li.get(i).toString())){
    			return i;
    		}
    	}
    	return 0;
    }
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
    	switch(id) {
    		case ConstDefine.ICON_LIST_DIALOG:
    			Builder builder = new AlertDialog.Builder(this);
    			BaseAdapter adapter = new ListItemAdapter();
    			DialogInterface.OnClickListener listener = 
    				new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int which) {
							/////////////////
							System.out.println("which"+which);
							if(which==0)
							{
							Map<String, String> params = new HashMap<String, String>();
	                         params.put("fileName", imageName);
	                         params.put("user_name", user_id);
	                         System.out.println("file:"+imagePath);
	                         File file=new File(imagePath);
	                       //  System.out.println("file:"+file.getAbsolutePath());
							 FormFile formfile = new FormFile(imageName,file , "image", "application/octet-stream");
							 try {
								SocketHttpRequester.post(com.wust.util.ConstDefine.URL+"uploadimageaction", params, formfile);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							}
							if(which==1)
							{
								System.out.println("删除");
							
							 File file1=new File(imagePath);
		                       //  System.out.println("file:"+file.getAbsolutePath());
								file1.delete();
							}
						}
					};
				builder.setAdapter(adapter, listener);
    			dialog = builder.create();
    			break;
    		
    	}
    	return dialog;
    }
    class ListItemAdapter extends BaseAdapter {
		public int getCount() {
			return 2;
		}
		public Object getItem(int position) {
			return null;
		}
		public long getItemId(int position) {
			return 0;
		}
		public View getView(int position, 
				View contentView, ViewGroup parent) {
			TextView textView = 
				new TextView(ImageSwitcherAndGalleryDemoActivity.this);
			//获得array.xml中的数组资源getStringArray返回的是一个String数组
			String text = getResources().getStringArray(R.array.selector)[position];
			textView.setText(text);
			//设置字体大小
			textView.setTextSize(24);
			AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
					LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
			textView.setLayoutParams(layoutParams);
			//设置水平方向上居中
			textView.setGravity(android.view.Gravity.CENTER_VERTICAL);
			textView.setMinHeight(65);
			//设置文字颜色
			textView.setTextColor(Color.BLACK);  
			//设置textView的左上右下的padding大小
			textView.setPadding(15, 0, 15, 0);
			//设置文字和图标之间的padding大小
			textView.setCompoundDrawablePadding(15);
			return textView;
		}
		
    	
    }
    /** 从SD卡中获取资源图片的路径 */
	private List<String> getImagePathFromSD() {
		/* 设定目前所在路径 */
		List<String> it = new ArrayList<String>();
		
		//根据自己的需求读取SDCard中的资源图片的路径
		
		
		File mFile = new File(ConstDefine.PATH);
		File[] files = mFile.listFiles();

		/* 将所有文件存入ArrayList中 */
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (checkIsImageFile(file.getPath()))
				it.add(file.getPath());
		}
		return it;
	}

	/** 判断是否相应的图片格式  */
	private boolean checkIsImageFile(String fName) {
		boolean isImageFormat;

		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 按扩展名的类型决定MimeType */
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			isImageFormat = true;
		} else {
			isImageFormat = false;
		}
		return isImageFormat;
	}

	/* 改写BaseAdapter自定义一ImageAdapter class */
	public class ImageAdapter extends BaseAdapter {
		/* 声明变量 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;
		
		/* ImageAdapter的构造符 */
		public ImageAdapter(Context c, List<String> li) {
			mContext = c;
			lis = li;
			
			/*
			 * 使用res/values/attrs.xml中的<declare-styleable>定义 的Gallery属性.
			 */
			TypedArray mTypeArray = obtainStyledAttributes(R.styleable.Gallery);
			/* 取得Gallery属性的Index id */
			mGalleryItemBackground = mTypeArray.getResourceId(
					R.styleable.Gallery_android_galleryItemBackground, 0);
			/* 让对象的styleable属性能够反复使用 */
			mTypeArray.recycle();
		}

		/* 重写的方法getCount,传回图片数目 */
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		/* 重写的方法getItem,传回position */
		public Object getItem(int position) {
			return position;
		}

		/* 重写的方法getItemId,传并position */
		public long getItemId(int position) {
			return position;
		}

		/* 重写方法getView,传并几View对象 */
		public View getView(int position, View convertView, ViewGroup parent) {
			/* 产生ImageView对象 */
			
			ImageView i = new ImageView(mContext);
			BitmapFactory.Options options = new BitmapFactory.Options(); 
			options.inSampleSize=4;
			/* 设定图片给imageView对象 */
			Bitmap bm = BitmapFactory.decodeFile(lis.get(position%lis.size()).toString(),options);
			 
			i.setImageBitmap(bm);
		
			/* 重新设定图片的宽高 */
			i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			/* 重新设定Layout的宽高 */
			i.setLayoutParams(new Gallery.LayoutParams(138, 90));
			/* 设定Gallery背景图 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 传回imageView对象 */
			return i;
		}
	} 
	  public  int computeSampleSize(BitmapFactory.Options options,
              int minSideLength, int maxNumOfPixels) {
          int initialSize = computeInitialSampleSize(options, minSideLength,
                  maxNumOfPixels);

          int roundedSize;
          if (initialSize <= 8) {
              roundedSize = 1;
              while (roundedSize < initialSize) {
                  roundedSize <<= 1;
              }
          } else {
              roundedSize = (initialSize + 7) / 8 * 8;
          }

          return roundedSize;
      }

      private  int computeInitialSampleSize(BitmapFactory.Options options,
              int minSideLength, int maxNumOfPixels) {
          double w = options.outWidth;
          double h = options.outHeight;

          int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                  .sqrt(w * h / maxNumOfPixels));
          int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
                  .floor(w / minSideLength), Math.floor(h / minSideLength));

          if (upperBound < lowerBound) {
              // return the larger one when there is no overlapping zone.
              return lowerBound;
          }

          if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
              return 1;
          } else if (minSideLength == -1) {
              return lowerBound;
          } else {
              return upperBound;
          }
      }
	@Override
	public View makeView() {
	    ImageView iv = new ImageView(this); 
	    iv.setBackgroundColor(0xFF000000); 
	    iv.setScaleType(ImageView.ScaleType.FIT_CENTER); 
	    iv.setLayoutParams(new ImageSwitcher.LayoutParams( 
	        LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
	    return iv; 
	}

	
	@Override  
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)  
    {  
	
		if(firstURL==null&&mindex!=position){
			System.out.println("index="+mindex);
			String photoURL = list[position];
			System.out.println("PhotoURL:"+photoURL);
			imagePath=photoURL;
	         imageName=photoURL.substring(photoURL.lastIndexOf("/")+1, photoURL.length());
			Log.i("A", photoURL);	
			mSwitcher.setImageURI(Uri.parse(photoURL));
			mindex=position;
		}   
    } 
	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		if(firstURL!=null){
			mGallery.setSelection(index);
			imagePath=firstURL;
	         imageName=firstURL.substring(firstURL.lastIndexOf("/")+1, firstURL.length());
			firstURL=null;
		}
	}
	
}